package com.phpxiu.app.view;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.CurLiveInfo;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.UserHomeContent;
import com.phpxiu.app.model.UserHomeInfo;
import com.phpxiu.app.model.UserHomeLiveInfo;
import com.phpxiu.app.model.event.OnBlockEvent;
import com.phpxiu.app.model.event.OnRefreshFollowCount;
import com.phpxiu.app.model.response.UserHomeModel;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.OKHttpResponseModel;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.custom.FrescoImageView;
import com.phpxiu.app.view.custom.WindowLayout;
import com.phpxiu.app.view.fragment.UserHomeFirstFragment;
import com.phpxiu.app.view.fragment.UserHomeSecondFragment;
import com.tencent.TIMConversationType;
import com.tencent.TIMFriendResult;
import com.tencent.TIMFriendshipManager;
import com.tencent.TIMManager;
import com.tencent.TIMValueCallBack;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by WuJinZhou on 2016/5/27.
 */
public class UserHome extends UIBase implements View.OnClickListener{
    public final static String TAG="UserHome";
    public final static String EXTRA_PARAM_KEY_UID="extra_param_key_uid";
    private final static ForegroundColorSpan SPAN=new ForegroundColorSpan(Color.parseColor("#7fFFFFFF"));
    public final static int HANDLE_MSG_FANS_COUNT_INCREASE=0x1;//粉丝数增加
    public final static int HANDLE_MSG_FANS_COUNT_DECREASE=0x2;//粉丝数减少
    private String uid;
    private UserHomeInfo mUser;
    private UserHomeContent mContent;
    private UserHomeLiveInfo mLiveInfo;
    private WindowLayout mainView;
    private LinearLayout topView;
    private ImageView homeMenuView,videoMenuView;
    private UserHomeFirstFragment firstFragment;
    private UserHomeSecondFragment secondFragment;
    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;
    private TextView costView;
    private SpannableStringBuilder costTxt=new SpannableStringBuilder();
    private FrescoImageView headView;
    private TextView IDView;//显示直播ID

    private TextView nickTv;
    private ImageView sexView;
    private FrescoImageView lvIconView;
    private String followLabel;
    private String fansLabel;
    private TextView followLinkView;
    private TextView fansLinkView;

    private int currentFansCount=0;
    private SpannableStringBuilder followLinkTxt=new SpannableStringBuilder();
    private SpannableStringBuilder fansLinkTxt=new SpannableStringBuilder();

    private TextView introView;
    private View bottomBar;//底部操作栏
    private RelativeLayout followMenu;//底部关注按钮
    private TextView followMenuTitle;//底部关注状态标题
    private ImageView followMenuIcon;//底部关注按钮图标
    private boolean isFollow=false;//是否关注

    private RelativeLayout chatMenu;

    private RelativeLayout blockOptionMenu;//黑名单操作
    private TextView blockTitleView;

    private OKHttpParam followParam;
    private boolean isRequestAttention=false;//正在请求关注操作
    private List<String>blackListIds=new ArrayList<String>();
    private boolean isBlocking=false;//正在黑名单操作

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_home);
        uid=getIntent().getStringExtra(EXTRA_PARAM_KEY_UID);
        if(uid==null||"".equals(uid)){
            finish();
            return;
        }
        init();
    }

    /**
     * 初始化
     */
    private void init(){
        mainView=(WindowLayout)findViewById(R.id.home_root_view);
        bottomBar=findViewById(R.id.user_home_bottom_bar);
        try {
            //是自己的主页，不显示操作
            if(uid.equals(MySelfInfo.getInstance().getId())){
                if(bottomBar.getVisibility()==View.VISIBLE){
                    bottomBar.setVisibility(View.GONE);
                }
            }
        }catch (NullPointerException e){
            e.printStackTrace();
        }
        findViewById(R.id.top_bar_back_btn).setOnClickListener(this);
        fragmentManager=getSupportFragmentManager();
        initTopView();
        initBottomMenus();
        initBar();
        homeMenuView.performClick();
        request();
    }

    /**
     * 初始化顶部视图
     */
    private void initTopView(){
        topView=(LinearLayout)findViewById(R.id.user_home_top_view);
        LinearLayout.LayoutParams params=(LinearLayout.LayoutParams)topView.getLayoutParams();
        params.height=KKYUtil.dip2px(this,255);
        topView.setLayoutParams(params);
        costView=(TextView)findViewById(R.id.user_home_cost_value_view);
        headView=(FrescoImageView)findViewById(R.id.user_head_view);
        headView.setOnClickListener(this);
        IDView=(TextView)findViewById(R.id.user_live_id_view);
        nickTv=(TextView)findViewById(R.id.user_nick);
        sexView=(ImageView)findViewById(R.id.user_sex_icon_view);
        lvIconView=(FrescoImageView)findViewById(R.id.user_lvl_icon_view);
        followLabel=getString(R.string.ui_user_follow_title);
        fansLabel=getString(R.string.ui_user_fans_label);
        followLinkView=(TextView)findViewById(R.id.user_follow_link);
        followLinkView.setOnClickListener(this);
        fansLinkView=(TextView)findViewById(R.id.user_fans_link);
        fansLinkView.setOnClickListener(this);
        introView=(TextView)findViewById(R.id.user_intro_view);
    }

    /**
     * 初始化底部菜单
     */
    private void initBottomMenus(){
        followMenu=(RelativeLayout)findViewById(R.id.attention_menu);
        followMenuIcon=(ImageView)findViewById(R.id.attention_menu_icon);
        followMenuTitle=(TextView)findViewById(R.id.attention_menu_title);

        chatMenu=(RelativeLayout)findViewById(R.id.private_msg_menu);
        chatMenu.setOnClickListener(this);
        blockOptionMenu=(RelativeLayout)findViewById(R.id.remove_user_menu);
        blockOptionMenu.setOnClickListener(this);
        blockTitleView=(TextView)findViewById(R.id.remove_user_menu_title);
    }
    /**
     * 初始化导航栏
     */
    private void initBar(){
        homeMenuView=(ImageView)findViewById(R.id.user_home_navigator_bar_home_menu_view);
        homeMenuView.setOnClickListener(this);
        videoMenuView=(ImageView)findViewById(R.id.user_home_navigator_bar_video_menu_view);
        videoMenuView.setOnClickListener(this);
    }


    /**
     * 刷新指示标志位置
     */
    private void refreshIndicator(int showPosition){
        homeMenuView.setImageResource(R.mipmap.user_home_model_home_normal);
        videoMenuView.setImageResource(R.mipmap.user_home_model_video_normal);
        transaction=fragmentManager.beginTransaction();
        hideFragments();
        switch (showPosition){
            case 0:
                if(firstFragment==null){
                    firstFragment=UserHomeFirstFragment.builder(null);
                    transaction.add(R.id.fragment_box,firstFragment);
                }else{
                    transaction.show(firstFragment);
                }
                if(mContent!=null){
                    firstFragment.update(mContent);
                }
                homeMenuView.setImageResource(R.mipmap.user_home_model_home_selected);
                break;
            case 1:
                videoMenuView.setImageResource(R.mipmap.user_home_model_video_selected);
                if(secondFragment==null){
                    secondFragment=UserHomeSecondFragment.builder(uid);
                    if(mLiveInfo!=null){
                        secondFragment.updateLive(mLiveInfo);
                    }
                    transaction.add(R.id.fragment_box,secondFragment);
                }else{
                    transaction.show(secondFragment);
                }
                break;
            default:
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    private void hideFragments(){
        if(firstFragment!=null){
            transaction.hide(firstFragment);
        }
        if(secondFragment!=null){
            transaction.hide(secondFragment);
        }
    }

    @Override
    public void handleMsg(Message msg) {
        switch (msg.what){
            case HANDLE_MSG_FANS_COUNT_INCREASE:
                currentFansCount++;
                refreshCount();
                break;
            case HANDLE_MSG_FANS_COUNT_DECREASE:
                if(currentFansCount>0){
                    currentFansCount--;
                }
                refreshCount();
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_bar_back_btn:
                onBackPressed();
                break;
            case R.id.user_home_navigator_bar_home_menu_view:
                refreshIndicator(0);
                break;
            case R.id.user_home_navigator_bar_video_menu_view:
                refreshIndicator(1);
                break;
            case R.id.user_fans_link:
                Intent fans=new Intent(this,UserFans.class);
                fans.putExtra(UserFans.EXTRA_PARAM_UID_KEY,uid);
                startActivity(fans);
                break;
            case R.id.user_follow_link:
                Intent attention=new Intent(this,UserFollow.class);
                attention.putExtra(UserFollow.EXTRA_PARAM_UID_KEY,uid);
                startActivity(attention);
                break;
            case R.id.attention_menu:
                if(!isRequestAttention) {
                    follow();
                }
                break;
            case R.id.private_msg_menu:
                if(mUser!=null){
                    gotoChat(mUser.getUid(),mUser.getUid(),mUser.getNickname(),mUser.getAvatar());
                }
                break;
            case R.id.remove_user_menu:
                //拉黑
                if(!isBlocking){
                    blackListOption();
                }
                break;
            case R.id.go_room_btn_right:
                if(mLiveInfo!=null) {
                    onEnterRoom();
                }
                break;
            case R.id.user_head_view:
                if(mUser!=null){
                    Intent preview=new Intent(this,PicturePreview.class);
                    preview.putExtra(PicturePreview.PREVIEW_ACTION,PicturePreview.SAVE);
                    preview.putExtra(PicturePreview.PREVIEW_URL,mUser.getAvatar());
                    preview.setData(Uri.parse(mUser.getAvatar()));
                    startActivity(preview);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 请求初始化
     */
    private void request(){
        OKHttpParam param=OKHttpParam.builder(false);
        param.put("uid",uid);
        OKHttp.post(HttpConfig.API_USER_HOME, param.jsonParam(), TAG, new OKHttpUIHandler(UserHomeModel.class) {
            @Override
            public void onSuccess(Object model) {
                UserHomeModel m = (UserHomeModel) model;
                KKYUtil.log(uid + "-->个人中心数据：" + m.getResponseStr());
                mContent = m.getData();
                mUser = mContent.getInfo();
                mLiveInfo = mContent.getLive();
                if(mLiveInfo!=null){
                    if(secondFragment!=null){
                        secondFragment.updateLive(mLiveInfo);
                    }
                }
                isFollow = "1".equals(mContent.getRelationship()) || "2".equals(mContent.getRelationship());//true是关注状态,false未关注
                if (isFollow) {
                    followMenuTitle.setText(getString(R.string.ui_user_followed_title));
                    followMenuIcon.setImageResource(R.mipmap.user_home_follow_icon);
                } else {
                    followMenuTitle.setText(getString(R.string.ui_user_follow_title));
                    followMenuIcon.setImageResource(R.mipmap.user_home_un_follow_icon);
                }
                followMenu.setOnClickListener(UserHome.this);
                if ("0".equals(mContent.getBlock())) {//未拉黑
                    blockTitleView.setText(getString(R.string.ui_user_blacklist_title));
                } else {
                    blockTitleView.setText(getString(R.string.ui_user_blacklisted_title));
                }
                refreshTopView();
            }

            @Override
            public void onErr(String errMsg) {

            }
        });
    }

    /**
     * 更新顶部区域内容
     */
    private void refreshTopView(){
        costTxt.clear();
        costTxt.append(getString(R.string.ui_user_cost_label)).append(" ").append(mUser.getSpend());
        costView.setText(costTxt);
        headView.setImageURI(Uri.parse(mUser.getAvatar()));
        IDView.setText("ID:"+mUser.getUid());
        nickTv.setText(mUser.getNickname());
        String sex=mUser.getSex();
        if("1".equals(sex)){
            sexView.setImageResource(R.mipmap.user_sex_icon_male);
        }else{
            sexView.setImageResource(R.mipmap.user_sex_icon_female);
        }
        if(!"".equals(mUser.getLvl())){
            lvIconView.setImageURI(Uri.parse("asset:///lvIcons/" + mUser.getLvl() + ".png"));
        }

        try {
            currentFansCount=Integer.parseInt(mUser.getFansnum());
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
        followLinkTxt.append(followLabel).append(" ").append(mUser.getFollownum());
        followLinkTxt.setSpan(SPAN,0,followLabel.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        followLinkView.setText(followLinkTxt);
        refreshCount();
        introView.setText(mUser.getIntro());
        if(firstFragment!=null){
            firstFragment.update(mContent);
        }

    }

    /**
     * 关注操作
     */
    private void follow(){
        if(followParam==null){
            followParam=OKHttpParam.builder(false);
        }
        followParam.put("uid",uid);
        String url=null;
        if(isFollow){
            url=HttpConfig.API_CANCEL_ATTENTION_USER;
        }else {//添加关注
            if("1".equals(mContent.getBlock())){//拉黑状态，取消拉黑
                if(isBlocking){
                    //mainView.showTopMsg(getString(R.string.room_user_card_request_msg));
                    return;
                }
                cancelBlackList(mUser.getUid(),HttpConfig.API_ADD_CANCEL_BLOCK_BY_UID);
            }
            url=HttpConfig.API_ATTENTION_USER;
        }
        isRequestAttention=true;
        OKHttp.post(url,followParam.jsonParam(),TAG,new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                isRequestAttention=false;
                if (isFollow) {
                    followMenuTitle.setText(getString(R.string.ui_user_follow_title));//取消关注成功，显示关注字样
                    //mainView.showTopMsg(getString(R.string.user_home_bottom_bar_un_follow_success));
                    handler.sendEmptyMessage(HANDLE_MSG_FANS_COUNT_DECREASE);
                    EventBus.getDefault().post(new OnRefreshFollowCount(false));//通知更新关注数量，减少
                    followMenuIcon.setImageResource(R.mipmap.user_home_un_follow_icon);
                } else {
                    handler.sendEmptyMessage(HANDLE_MSG_FANS_COUNT_INCREASE);
                    EventBus.getDefault().post(new OnRefreshFollowCount(true));//通知更新关注数量，增加
                    followMenuTitle.setText(getString(R.string.ui_user_followed_title));//关注成功，显示取消关注字样
                    //mainView.showTopMsg(getString(R.string.user_home_bottom_bar_follow_success));
                    followMenuIcon.setImageResource(R.mipmap.user_home_follow_icon);
                }
                isFollow = !isFollow;
            }

            @Override
            public void onErr(String errMsg) {
                isRequestAttention=false;
                mainView.showTopMsg(errMsg);
            }
        });
    }

    /**
     * 跳转到聊天界面
     * @param peer
     * @param uid
     * @param nick
     * @param avatar
     */
    private void gotoChat(String peer,String uid,String nick,String avatar){
        Intent chat=new Intent(this, C2CChat.class);
        chat.putExtra(C2CChat.EXTRA_CONVERSATION_ID, peer);
        chat.putExtra(C2CChat.EXTRA_USER_ID, uid);
        chat.putExtra(C2CChat.EXTRA_USER_NICK_NAME,nick);
        chat.putExtra(C2CChat.EXTRA_USER_AVATAR,avatar);
        startActivity(chat);
    }

    /**
     * 黑名单操作
     */
    private void blackListOption(){
        if(mContent==null||mUser==null){
            return;
        }
        isBlocking=true;
        if("0".equals(mContent.getBlock())){//未拉黑，做拉黑操作
            addBlackList(mUser.getUid(),HttpConfig.API_ADD_BLOCK_BY_UID);
        }else{
            cancelBlackList(mUser.getUid(),HttpConfig.API_ADD_CANCEL_BLOCK_BY_UID);
        }
    }

    /**
     * 拉入黑名单
     */
    private void addBlackList(final String uid,final String url){
        blackListIds.clear();
        blackListIds.add(uid);
        if(isFollow){//如果当前主页是我关注的人，则刷新我的关注数
            isFollow=false;
            mContent.setRelationship("0");
            followMenuTitle.setText(getString(R.string.ui_user_follow_title));//取消关注成功，显示关注字样
            handler.sendEmptyMessage(HANDLE_MSG_FANS_COUNT_DECREASE);
            EventBus.getDefault().post(new OnRefreshFollowCount(false));//通知更新关注数量，减少
            followMenuIcon.setImageResource(R.mipmap.user_home_un_follow_icon);
        }
        TIMFriendshipManager.getInstance().addBlackList(blackListIds,new TIMValueCallBack<List<TIMFriendResult>>() {
            @Override
            public void onError(int i, String s) {
                isBlocking=false;
            }

            @Override
            public void onSuccess(List<TIMFriendResult> timFriendResults) {
                mContent.setBlock("1");
                isBlocking=false;
                EventBus.getDefault().post(new OnBlockEvent(uid));//黑名单通知
                TIMManager.getInstance().deleteConversation(TIMConversationType.C2C,uid);
                blockTitleView.setText(getString(R.string.ui_user_followed_title));
                blockOption(url,uid);
                KKYUtil.log("黑名单添加成功");
            }
        });
    }

    /**
     * 取消黑名单
     * @param uid
     * @param url
     */
    private void cancelBlackList(final String uid,final String url){
        blackListIds.clear();
        blackListIds.add(uid);
        TIMFriendshipManager.getInstance().delBlackList(blackListIds, new TIMValueCallBack<List<TIMFriendResult>>() {
            @Override
            public void onError(int i, String s) {
                isBlocking=false;
            }

            @Override
            public void onSuccess(List<TIMFriendResult> timFriendResults) {
                mContent.setBlock("0");
                isBlocking=false;
                blockTitleView.setText(getString(R.string.ui_user_blacklist_title));
                blockOption(url, uid);
                KKYUtil.log("黑名单取消成功");
            }
        });
    }

    /**
     * 黑名单数据同步
     */
    private void blockOption(String url,String uid){
        OKHttpParam param=OKHttpParam.builder(false);
        param.put("uid",uid);
        OKHttp.post(url,param.jsonParam(),TAG,new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                KKYUtil.log("黑名单操作成功");
            }

            @Override
            public void onErr(String errMsg) {

            }
        });
    }

    /**
     * 进入直播间
     */
    public void onEnterRoom() {
        KKYUtil.log(TAG,"进入直播间："+mLiveInfo.getAvRoomId()+"@"+mLiveInfo.getTitle());
        try {
            Intent intent = new Intent(this,RoomVideoRoom.class);
            intent.putExtra(Constants.ID_STATUS, Constants.MEMBER);
            MySelfInfo.getInstance().setIdStatus(Constants.MEMBER);
            CurLiveInfo.setHostID(mLiveInfo.getHost().getUid());
            CurLiveInfo.setHostName(mLiveInfo.getHost().getNickname());
            CurLiveInfo.setHostAvator(mLiveInfo.getHost().getAvatar());
            CurLiveInfo.setRoomNum(Integer.parseInt(mLiveInfo.getAvRoomId()));
            CurLiveInfo.setMembers(Integer.parseInt(mLiveInfo.getWatchCount()) + 1); // 添加自己
            CurLiveInfo.setAdmires(Integer.parseInt(mLiveInfo.getAdmireCount()));
            CurLiveInfo.setAddress(mLiveInfo.getLbs().getAddress());
            startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 刷新关注数
     */
    private void refreshCount(){
        fansLinkTxt.clear();
        fansLinkTxt.append(fansLabel).append(" ").append(currentFansCount+"");
        fansLinkTxt.setSpan(SPAN,0,fansLabel.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        fansLinkView.setText(fansLinkTxt);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
